import { Message } from 'element-ui';
import { userLogin } from '@/api/login';
import { set, get } from '@/common/utils';
import router from '@/router';

export default {
  state: {
    user: get('user') || {},
  },
  mutations: {
    saveUser(state, payload) {
      state.user = payload.user;
    },
  },
  actions: {
    async login({ commit }, { name, password }) {
      try {
        const result = await userLogin({
          username: name,
          password,
        });
        commit('saveUser', { user: result.user });
        set('user', result.user);
        router.push('/admin');
      } catch (error) {
        Message.error('用户名或密码出错了');
      }
    },
    logout({ commit }) {
      commit('saveUser', { user: null });
      set('user', null);
      router.push('/login');
    },
  },
};
